package com.changba.schedule.controller;

import com.changba.schedule.service.ScheduleService;
import com.chongba.entity.ResponseMessage;
import com.chongba.entity.Task;
import com.chongba.exception.ScheduleSystemException;
import com.chongba.exception.TaskNotExistException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/schedule")
public class ScheduleController {

    @Autowired
    private ScheduleService scheduleService;

    //添加任务
    @PostMapping("/push")
    public ResponseMessage pushTask(@RequestBody Task task) {
        try {
            Long taskId = scheduleService.addTask(task);
            return ResponseMessage.ok(taskId);
        } catch (ScheduleSystemException e) {
            e.printStackTrace();
            return ResponseMessage.error(task);
        }
    }

    //消费任务
    @GetMapping("/poll/{taskType}/{priority}")
    public ResponseMessage pollTask(@PathVariable("taskType") int taskType,
                                    @PathVariable("priority") int priority) {
        try {
            Task task = scheduleService.poll(taskType, priority);
            return ResponseMessage.ok(task);
        } catch (TaskNotExistException e) {
            e.printStackTrace();
            return ResponseMessage.error(e.getMessage());
        }
    }

    //取消任务
    @PostMapping("/cancel/{taskId}")
    public ResponseMessage cancelTask(@PathVariable("taskId") Long taskId) {
        try {
            boolean result = scheduleService.cancelTask(taskId);
            return ResponseMessage.ok(result);
        } catch (TaskNotExistException e) {
            e.printStackTrace();
            return ResponseMessage.error(e.getMessage());
        }
    }

    //对外提供缓存数据刷新接口
    @GetMapping("/refresh")
    public ResponseMessage refresh() {
        try {
            scheduleService.refresh();
            return ResponseMessage.ok("刷新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMessage.error(e.getMessage());
        }

    }

}
